package com.linkage.educloud.ah.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.linkage.educloud.ah.mvp.ABasicPresenter;
import com.zzhou.common.library.util.LogUtils;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * <desc>
 * Created by The Moss on 2018/6/8.
 */

public abstract class BasicFragment extends AbstractFragment {
    protected abstract int attachLayoutRes();

    Unbinder unBinder;
    protected boolean isFirstVisible = true;
    View contentView;
    ABasicPresenter iPresenter;
    protected FragmentManager fragmentManager;
    protected FragmentTransaction fragmentTransaction;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(attachLayoutRes(), container, false);
        unBinder = ButterKnife.bind(this, contentView);
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        return contentView;
    }

    protected void initView(ABasicPresenter iPresenter) {
        if (iPresenter != null) {
            this.iPresenter = iPresenter;
        }
    }

    ;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getUserVisibleHint()) {
            if (isFirstVisible) {
                isFirstVisible = false;
                onFragmentVisibleChange(true);
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (contentView == null) {
            LogUtils.d(this.getClass().getSimpleName(), "contentView == null");
            return;
        }
        if (isFirstVisible && isVisibleToUser) {
            isFirstVisible = false;
            onFragmentVisibleChange(true);
            return;
        }
    }

    protected void onFragmentVisibleChange(boolean isVisible) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unBinder != null) {
            unBinder.unbind();
        }
        if (iPresenter != null) {
            iPresenter.onDestory();
        }
    }

    @Override
    protected boolean onBackPressed() {
        return false;
    }
}
